﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Windows;
using MemoryCheck.DataAccess;
using MSPToolkit.Encodings;
using System.IO.IsolatedStorage;

namespace TBR.Common
{
    public class WebHelper
    {
        #region events
        public delegate void RequestEventHandler(object source, RequestEventArgs args);
        public class RequestEventArgs : EventArgs
        {
            public string HtmlCode;
        }
        public event RequestEventHandler RequestCompleted;
        public void OnRequestCompleted()
        {
            if (RequestCompleted != null)
            {
                RequestEventArgs args = new RequestEventArgs();
                args.HtmlCode = HtmlResponse;
                RequestCompleted(this, args);
            }
        }
        #endregion

        #region properties
        private string HtmlResponse { get; set; }
        private CookieContainer cookieContainer { get; set; }
        private bool IsExtractCookies { get; set; }
        private Uri Uri { get; set; }
        #endregion

        #region public methods
        public void GetHtmlCode(Uri uri, Method method, Dictionary<string, string> formDataParams = null, Cookie cookie = null, bool isExtractCookies = false)
        {
            IsExtractCookies = isExtractCookies;
            Uri = uri;
            var request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = method == 0 ? "GET" : "POST";
            request.CookieContainer = new CookieContainer();
            var cookiesFromIsolatedStorage = CookieHelper.GetCookiesFromIsolatedStorage();
            if (cookiesFromIsolatedStorage != null) request.CookieContainer.SetCookies(uri, cookiesFromIsolatedStorage);
            if (cookie != null)
            {
                CookieCollection cookieCollection = new CookieCollection();
                cookieCollection.Add(cookie);
                request.CookieContainer.Add(uri, cookieCollection);
            }
            //request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
            //request.ContentLength = 84;
            //request.Headers["Origin"] = "http://tabor.ru";
            //request.Headers["Referer"] = "http://tabor.ru/";
            //request.CookieContainer = cookieContainer;
            //request.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
            //request.AllowReadStreamBuffering = false;
            if (method == Method.Get)
            {
                request.BeginGetResponse(new AsyncCallback(this.GetResponse), request);
            }
            else
            {
                request.ContentType = "text/html; charset=cp1251";
                request.ContentType = "application/x-www-form-urlencoded; charset=cp1251";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                request.Headers["Accept-Language"] = "en-US,en;q=0.8,ru;q=0.6,be;q=0.4";
                request.Headers["Cache-Control"] = "max-age=0";
                request.Headers["Connection"] = "keep-alive";
                request.Headers["Host"] = "tabor.ru";
                byte[] postBytes = new Windows1251Encoding().GetBytes(GetPostParametersByDictionary(formDataParams));
                IAsyncResult asyncResult = request.BeginGetRequestStream(
                x =>
                {
                    using (var stream = request.EndGetRequestStream(x))
                    {
                        stream.Write(postBytes, 0, postBytes.Length);
                    }
                    request.BeginGetResponse(this.GetResponse, request);
                },
                null);
            }
        }
        #endregion

        #region private methods
        private string GetPostParametersByDictionary(Dictionary<string, string> postParams)
        {
            string strPostParams = String.Empty;
            foreach (var param in postParams)
            {
                strPostParams += String.Format("{0}={1}&", param.Key, param.Value);
            }
            return strPostParams.Remove(strPostParams.Length - 1);
        }

       

        private void GetResponse(IAsyncResult ar)
        {
            try
            {
                var request = (HttpWebRequest)ar.AsyncState;
                var response = (HttpWebResponse)request.EndGetResponse(ar);
                if (IsExtractCookies)
                {
                    //var cookieContainer = new CookieContainer();
                    //cookieContainer.SetCookies(Uri, response.Headers["Set-Cookie"]);
                    CookieHelper.SaveCookiesToIsolatedStorage(response.Headers["Set-Cookie"]);
                }
                HtmlResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                 {
                     OnRequestCompleted();
                 });
            }
            catch (Exception e)
            {

            }
        }
      
        #endregion

        #region enums
        public enum Method
        {
            Get = 0,
            Post = 1
        }
        #endregion
    }
}
